﻿#include "mywidget.h"

#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QPainter>
#include <QPrinter>
#include <QPrintPreviewDialog>
#include <QDateTime>


#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

MyWidget::MyWidget(QWidget *parent) : QWidget(parent) {
    QVBoxLayout *layout = new QVBoxLayout(this);
    QPushButton *printButton = new QPushButton("Print Preview", this);
    layout->addWidget(printButton);
    strHarwareName = "Recording001.pnrf";
    connect(printButton, &QPushButton::clicked, this, &MyWidget::onPrintPreview);
}

//
//void MyWidget::paintEvent(QPaintEvent *event) {
//    QDialog::paintEvent(event);
//    // 更多绘制指令...
//}


void MyWidget::onPrintPreview() {
    QPrinter printer;
    QPrintPreviewDialog preview(&printer, this);
    preview.setWindowFlags(windowFlags() | Qt::Window | Qt::WindowCloseButtonHint | Qt::WindowMinMaxButtonsHint);
    connect(&preview, &QPrintPreviewDialog::paintRequested, this, &MyWidget::onPaintRequested);
    preview.exec();
}

void MyWidget::onPaintRequested(QPrinter *printer) {
    QPainter painter;
    if (!painter.begin(printer)) {
        qWarning("Failed to open the printer.");
        return;
    }
    // 在这里添加你的绘制代码
    //painter.drawText(100, 100, "Hello from Print Preview!");
    myCustomPainting(&painter);
    painter.end();
}

void MyWidget::myCustomPainting(QPainter *painter) {
    QPrinter *printer = dynamic_cast<QPrinter*>(painter->device());
    if (!printer) {
        // 屏幕预览的绘制逻辑（略）
        return;
    }

    // 页面参数
    const QRectF pageRect = printer->pageRect(QPrinter::DevicePixel);
    const qreal margin = 50;
    const qreal headerHeight = 40;
    const qreal footerHeight = 40;
    const qreal usableHeight = pageRect.height() - 2 * margin - headerHeight - footerHeight;

    // 字体设置
    QFont contentFont("Arial", 30);
    QFont headerFont("Arial", 12);
    QFont footerFont("Arial", 10);
    painter->setFont(contentFont);
    QFontMetrics metrics(contentFont);
    const qreal lineHeight = metrics.height();

    // 分页控制
    int pageNumber = 1;
    qreal currentY = margin + headerHeight;
    const QString timestamp = QDateTime::currentDateTime().toString("yyyy年MM月dd日 HH:mm:ss");

    // 绘制首頁页眉
    painter->save();
    painter->setFont(headerFont);

    QFontMetrics headerMetrics(headerFont);
    qreal timestampWidth = headerMetrics.horizontalAdvance(timestamp); // 获取宽度
    qreal timeMargin = pageRect.width() - timestampWidth - margin;

    // 头的高度
    //qreal headerHeight = headerMetrics.height();


    painter->drawText(margin, margin + 20, strHarwareName);

    painter->drawText(timeMargin, margin + 20, timestamp);

    currentY += headerMetrics.height();
    painter->restore();

    for (int i = 0; i < 100; i++) {
        paintContent(painter, printer, "AAAAAA", timestamp, currentY, pageNumber, pageRect, timeMargin, lineHeight, margin, headerHeight, usableHeight);
    }
    
    //// 这里需要封装起来作为一个方法
    //for(int i = 0; i < 100; i++) {
    //    // 换页判断
    //    if (currentY + lineHeight > margin + headerHeight + usableHeight) {
    //        // 绘制当前页的页脚
    //        painter->save();
    //        painter->setFont(footerFont);
    //        painter->drawText(QRectF(margin, pageRect.height() - margin - 20,
    //                              pageRect.width() - 2*margin, footerHeight),
    //                         Qt::AlignRight,
    //                         QString("第 %1 页").arg(pageNumber));
    //        painter->restore();

    //        // 换新页
    //        printer->newPage();
    //        pageNumber++;

    //        // 绘制新页的页眉
    //        painter->save();
    //        painter->setFont(headerFont);
    //        painter->drawText(timeMargin, margin + 20, timestamp);
    //        painter->restore();

    //        currentY = margin + headerHeight; // 重置绘制位置
    //    }

    //    // 绘制内容
    //    painter->drawText(margin, currentY, "Custom Text");
    //    currentY += lineHeight;
    //}

    // 绘制最后一页的页脚（无论是否满页）
    painter->save();
    painter->setFont(footerFont);
    painter->drawText(QRectF(margin, pageRect.height() - margin - 20,
                            pageRect.width() - 2*margin, footerHeight),
                     Qt::AlignRight,
                     QString("第 %1 页").arg(pageNumber));
    painter->restore();
}

void MyWidget::paintContent(QPainter* painter, QPrinter* printer, const QString& strContent, const QString& strTime, qreal& currentY,
    int & pageNumber, const QRectF &pageRect, qreal timeMargin, qreal lineHeight, qreal margin, qreal headerHeight, qreal usableHeight)
{
    const qreal footerHeight = 40;
    QFont headerFont("Arial", 12);
    QFont footerFont("Arial", 10);
    if (currentY + lineHeight > margin + headerHeight + usableHeight) {
        // 绘制当前页脚
        painter->save();
        painter->setFont(footerFont);
        painter->drawText(QRectF(margin, pageRect.height() - margin - 20,
            pageRect.width() - 2 * margin, footerHeight),
            Qt::AlignRight,
            QString("第 %1 页").arg(pageNumber));
        painter->restore();

        // 换新页
        printer->newPage();
        pageNumber++;

        // 绘制新页的页眉
        painter->save();
        painter->setFont(headerFont);
        painter->drawText(margin, margin + 20, strHarwareName);
        painter->drawText(timeMargin, margin + 20, strTime);
        painter->restore();

        currentY = margin + 20 + headerHeight; // 重置绘制位置
    }
    painter->drawText(margin, currentY, strContent);
    currentY += lineHeight;
}